import config from "./config.js"
import * as apis from "@/apis/modules/app.js"

const {baseUrl} = config

const uniHistory = {
	push: (url) => {
		uni.navigateTo({
			url
		})
	},

	back: (delta = 1) => {
		uni.navigateBack({
			delta
		})
	},

	goBack: () => {
		uni.navigateBack({
			delta: 1
		})
	},

	replace: (url) => {
		uni.redirectTo({
			url
		})
	},

	reLaunch: (url) => {
		uni.reLaunch({
			url
		})
	},

	switchTab: (url) => {
		uni.switchTab({
			url
		})
	}
}

const uploadFile = (file, cb) => {
	wx.uploadFile({
		url: `${baseUrl}/admin/sys-file/upload`, // 仅为示例，非真实的接口地址
		filePath: file.url,
		name: 'file',
		// formData: { user: 'test' },
		success: ({
			data: res
		}) => {
			// 上传完成需要更新 fileList
			const {
				data
			} = JSON.parse(res)
			file.fileUrl = data.url

			cb && cb(file)
		},
		fail: () => {}
	})
}

const logout = () => {
	uni.clearStorageSync('userInfo')
	uni.reLaunch({
		url: '/pages/login/index'
	})
}

const message = {
	info: (param, type = 'none') => {
		if (typeof param === 'string') {
			uni.showToast({
				title: param,
				duration: 3000,
				icon: type
			})
		} else {
			const {
				title,
				duration = 3000,
				cb
			} = param
			uni.showToast({
				title,
				duration,
				icon: type
			})

			setTimeout(() => {
				cb()
			}, duration)
		}
	},

	success: (param) => message.info(param, 'success'),
	error: (param) => message.info(param, 'error'),
}

const refreshToken = () => {
		const userInfo = uni.getStorageSync('userInfo')
	
		if (!userInfo) return logout()
	
		const {refresh_token} = userInfo
		
		apis.refreshToken(refresh_token)
			.then(({error, data}) => {
				if (error) return logout()
				
				wx.setStorageSync('userInfo', data)
				uniHistory.push('/pages/home/home')
			})
	}

export {
	uploadFile,
	logout,
	message,
	uniHistory,
	refreshToken
}
